import { app, BrowserWindow, ipcMain, Menu, nativeTheme, net } from "electron";
import path from "path";
import logColor from "colors-console";
import MainElectron from "./main-electron";
import { getDoNotDisturb } from "electron-notification-state";

console.log(getDoNotDisturb());
const platform = process.platform || os.platform();

// 屏蔽案例警告
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";

try {
  if (platform === "win32" && nativeTheme.shouldUseDarkColors === true) {
    require("fs").unlinkSync(
      path.join(app.getPath("userData"), "DevTools Extensions")
    );
  }
} catch (_) {
  console.log(logColor("red", "DevTools Extensions"));
}

/** @type {MainElectron} */
let electron;
/** @type {Electron.BrowserWindow} */
let mainWindow;

app.whenReady().then(async () => {
  electron = new MainElectron();
  mainWindow = await electron.createMainWindow({
    show: true,
    frame: false,
    width: 400,
    height: 400,
    backgroundColor: "#00000000",
    transparent: true,
    webPreferences: { preload: true },
    extendOption: { devtools: false },
  });
  electron.enableAutoUpdate(mainWindow.webContents);
});

app.on("web-contents-created", (e, webContents) => {
  webContents.setWindowOpenHandler((details) => {
    webContents.send("sendToHost", "new-window", details);
    return { action: "deny" };
  });
});

app.on("activate", () => {
  if (electron.isDestroyed(mainWindow)) {
    // console.log("重新创建主窗口");
    // mainWindow = electron.createMainWindow();
  } else {
    // console.log("发送 appActivate");
    // mainWindow.webContents.send("appActivate");
  }
});

ipcMain.handle("startMainWindow", async () => {
  mainWindow = await electron.createMainWindow();
});

ipcMain.handle("createView", async (event, name, options) => {
  await electron.createView(name, options);
  return true;
});

/**
 * 创建窗口
 */
ipcMain.handle("createWindow", async (e, name, options) => {
  const win = await electron.createWindow(name, options);
  return win.id;
});

ipcMain.handle("showWindow", (e, id) => {
  return new Promise((resolve) => {
    const win = BrowserWindow.fromId(id);
    if (!win.isDestroyed()) {
      win.show();

      win.webContents.on("ipc-message", function (event, channel, ...args) {
        if (channel === "close") {
          win.webContents.close();
          resolve(args[0]);
        }
      });
    }
  });
});

/**
 * 获取当前窗口Cookies
 */
ipcMain.handle("getCurrentCookies", async (event, url) => {
  return await electron.getWebCookie(event.sender, url);
});

ipcMain.handle("clientRequest", async (event, options, data, headers) => {
  return new Promise((resolve, reject) => {
    if (!options.method || options.method === "GET") {
      const uri = new URL(options.url);
      if (data) {
        uri.search = require("querystring").encode(data);
        data = null;
      }
      options.url = uri.href;
    }
    const request = net.request(options);

    let output = {
      options,
      headers,
      data,
      status: 0,
      response: "",
      redirect: {
        is: false,
        status: 0,
        method: null,
        url: null,
      },
    };

    request.on("error", (err) => {
      console.log("error", err);
      reject(err);
    });
    request.on("redirect", (statusCode, method, redirectUrl) => {
      output.redirect.is = true;
      output.redirect.status = statusCode;
      output.redirect.method = method;
      output.redirect.url = redirectUrl;
    });
    request.on("response", (response) => {
      output.status = response.statusCode;
      response.on("end", () => {
        output.response = output.response.toString();
        try {
          output.response = JSON.parse(output.response);
        } catch (error) {}
        resolve(output);
      });
      response.on("data", (chunk) => {
        output.response += chunk;
      });
    });

    if (headers) {
      for (const key in headers) {
        if (Object.hasOwnProperty.call(headers, key)) {
          request.setHeader(key, headers[key]);
        }
      }
    }
    request.end(JSON.stringify(data));
  });
});

ipcMain.handle("notify", (event, options) => {
  electron.notify(options);
});
